//
//  XXString.swift
//  XXSwiftDemo
//
//  Created by admin on 2022/3/25.
//

import UIKit
import CommonCrypto

func isEmpty(str: String?) -> Bool {
   if str == nil {
       return true
   } else if (str == "") {
       return true
   } else if (str == "<null>") {
       return true
   } else if (str == "(null)") {
       return true
   } else if (str == "null") {
       return true
   }
   return false
}

public extension String {
    
    var array:Array<Any>?{
        if let data = self.data(using: String.Encoding.utf8) {
            let arr = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
            return arr as? Array<Any>
        }
        return nil
    }
    
    var dic:Dictionary<String, Any>?{
        if let data = self.data(using: .utf8) {
            let dic = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
            return dic as? Dictionary<String, Any>
        }
        return nil
    }
    
    var url:URL?{
        if let str = self.urlEncoded(){
            return URL.init(string: str)
        }
        return nil
    }
    
    var data:Data?{
        return self.data(using: .utf8)
    }
    
    var md5:String {
            let utf8 = cString(using: .utf8)
            var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
            CC_MD5(utf8, CC_LONG(utf8!.count - 1), &digest)
            return digest.reduce("") { $0 + String(format:"%02X", $1) }
        }
    
    // URL编码 解码
    func urlEncoded() -> String? {
        return self.addingPercentEncoding(withAllowedCharacters:
                                                .urlQueryAllowed)
    }
    func urlDecoded() -> String? {
        return self.removingPercentEncoding
    }
    
    var number:NSNumber {
        return NumberFormatter.init().number(from: self) ?? 0
    }
    
    var int:Int {
        return self.number.intValue
    }
    
    var float:Float {
        return self.number.floatValue
    }
    
    var double:Double {
        return self.number.doubleValue
    }
    
    var bool:Bool {
        let number = self.int
        if (number > 0) {
            return true;
        }
        let lowercased = self.lowercased()
        switch lowercased {
        case "true", "yes", "1":
            return true;
        case "false", "no", "0":
            return false;
        default:
            return false;
        }
    }

    // 计算Size
    func sizeFor(size:CGSize, font:UIFont) -> CGSize {
        let rec:CGRect = self.boundingRect(with: size, options: NSStringDrawingOptions.usesFontLeading, attributes: [.font:font], context:nil)
        return rec.size
    }
    
    subscript (i:Int)->String{
        let startIndex = self.index(self.startIndex, offsetBy: i)
        let endIndex = self.index(startIndex, offsetBy: 1)
        return String(self[startIndex..<endIndex])
    }
    // String使用下标截取字符串  str[1..<4]
    subscript (r: Range<Int>) -> String {
        get {
            let startIndex = self.index(self.startIndex, offsetBy: r.lowerBound)
            let endIndex = self.index(self.startIndex, offsetBy: r.upperBound)
            return String(self[startIndex..<endIndex])
        }
    }
    // String使用下标截取字符串 str[1,2]
    subscript (index:Int , length:Int) -> String {
        get {
            let startIndex = self.index(self.startIndex, offsetBy: index)
            let endIndex = self.index(startIndex, offsetBy: length)
            return String(self[startIndex..<endIndex])
        }
    }
    // 截取 从头到i位置
    func substring(to:Int) -> String{
        return self[0..<to]
    }
    // 截取 从i到尾部
    func substring(from:Int) -> String{
        return self[from..<self.count]
    }
    // 替换字符
    func replac(_ of:String, _ with:String) -> String{
        return self.replacingOccurrences(of: of, with: with)
    }
    // 过滤字符
    func filter(_ strings:String...) -> String{
        var string = self
        for str in strings{
            string = string.replacingOccurrences(of: str, with: "")
        }
        return string
    }
    func range(_ str:String) -> Bool{
        return (self.range(of: str) != nil)
    }
    // 获取两个字符串直接的字符串
    func getSubStr(beginStr: String, endStr: String) -> String {
        let tempStr: NSString = NSString.init(string: self)
        let starRange = tempStr.range(of: beginStr)
        let endRange = tempStr.range(of: endStr)
        let range: NSRange! = NSMakeRange(starRange.location + starRange.length, endRange.location - starRange.location - starRange.length)
        let lastStr: String? = tempStr.substring(with: range)
        return lastStr ?? self
    }
    static func isEmptyString(str: String?) -> Bool {
        if str == nil {
            return true
        } else if (str == "") {
            return true
        } else if (str == "<null>") {
            return true
        } else if (str == "(null)") {
            return true
        } else if (str == "null") {
            return true
        }
        return false
    }
    
    /// 根据正则表达式判断
    ///
    /// - Parameter format: 正则表达式的样式
    /// - Returns: Bool
    func evaluate(format: String) -> Bool {
        let predicate = NSPredicate.init(format: "SELF MATCHES %@", format);
        return predicate.evaluate(with: self);
    }
    
    // 邮箱的正则表达式
    func isEmail() -> Bool {
        let format = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
        return self.evaluate(format: format);
    }
    
    // IP地址的正则表达式
    func isIp() -> Bool {
        let format = "((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)"
        return self.evaluate(format: format);
    }
    
    // HTTP链接 (例如 http://www.baidu.com )
    func isHTTP() -> Bool {
        let format = "([hH]ttp[s]{0,1})://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\-~!@#$%^&*+?:_/=<>.\',;]*)?"
        return self.evaluate(format: format);
    }
}

public extension String {

    // 大部分 switch 比对调用 此方法  ~=
    static func ~= (pattern:(String) -> Bool,value: String) -> Bool{
        pattern(value)
    }
    
    func hasPrefix(_ prefix:String) ->((String) -> Bool){ {$0.hasPrefix(prefix)} }
    func hasSuffix(_ suffix:String) ->((String) -> Bool){ {$0.hasSuffix(suffix)} }
    
    func test(){
        
        let str = "123456"
        switch str{
        case hasPrefix("123"):
            print("123开头")
        case hasSuffix("456"):
            print("456结尾")
        default:
            break
        }
    }
}
